package com.xing.servlet.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.util.StringUtils;
import com.xing.dao.BaseDao;
import com.xing.pojo.Role;
import com.xing.pojo.User;
import com.xing.service.role.RoleService;
import com.xing.service.role.RoleServiceImpl;
import com.xing.service.user.UserService;
import com.xing.service.user.UserServiceImpl;
import com.xing.util.Constants;
import com.xing.util.PageSupport;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//用户视图解析
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        System.out.println("进入UserServlet--doGet");
        String method = req.getParameter("method");
        System.out.println("method: " + method);
        if (method != null && method.equals("savepwd")) { //保存密码
            this.updatePwd(req, resp);
        } else if (method != null && method.equals("pwdmodify")) { //检查原密码是否正确
            this.pwdModify(req, resp);
        } else if (method != null && method.equals("query")) { //用户信息查询
            try {
                this.query(req, resp);
            } catch (SQLException throwables) {
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        } else if (method != null && method.equals("add")) { //添加用户
            try {
                this.addUser(req, resp);
            } catch (ParseException e) {
                e.printStackTrace();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }else if (method != null && method.equals("getrolelist")) { // 用户角色列表查询
            try {
                this.getRoleList(req,resp);
            } catch (SQLException throwables) {
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

        }else if (method != null && method.equals("modify")) {
            try {
                this.modifyUser(req, resp);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }else if (method != null && method.equals("deluser")) { // 删除用户
            try {
                this.delUser(req, resp);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if (method != null && method.equals("view")) {   //根据id查看单个用户信息
            try {
                this.getUserById(req, resp);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }else if (method != null && method.equals("ucexist")) { //用户编码是否存在
            try {
                this.userCodeExist(req, resp);
            } catch (SQLException throwables) {
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    //修改密码
    public void updatePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从Session里面拿Id
        Object attribute = req.getSession().getAttribute(Constants.USER_SESSION);
        String newPassword = req.getParameter("newpassword");

        boolean flag = false;

        if (attribute != null && !StringUtils.isNullOrEmpty(newPassword)) {
            UserServiceImpl userService = new UserServiceImpl();

            try {
                flag = userService.updatePwd(((User) attribute).getId(), newPassword);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            if (flag) {
                req.setAttribute("message", "密码修改成功，请重新登录");
                //密码修改成功，移除当前Session
                req.getSession().removeAttribute(Constants.USER_SESSION);
            } else {
                req.setAttribute("message", "密码修改失败");
            }
        } else {
            req.setAttribute("message", "新密码有问题");
        }
        req.getRequestDispatcher("pwdmodify.jsp").forward(req, resp);
    }

    //验证旧密码,Session中有用户的密码
    public void pwdModify(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //从Session里面拿Id
        Object attribute = req.getSession().getAttribute(Constants.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");

        //万能的Map
        Map<String, String> resultMap = new HashMap<>();

        if (attribute == null) { //Session失效了，session过期了
            resultMap.put("result", "sessionerror");
        } else if (StringUtils.isNullOrEmpty(oldpassword)) { //输入的密码为空
            resultMap.put("result", "error");
        } else {
            String userPassword = ((User) attribute).getUserPassword();//session中用户的密码
            if (oldpassword.equals(userPassword)) {
                resultMap.put("result", "true");
            } else {
                resultMap.put("result", "false");
            }
        }
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        writer.write(JSONArray.toJSONString(resultMap));
        writer.flush();
        writer.close();
    }

    //查询用户
    public void query(HttpServletRequest req, HttpServletResponse resp) throws SQLException, ClassNotFoundException, ServletException, IOException {
        //查询用户列表
        //从前端获取数据
        String queryUserName = req.getParameter("username");
        String temp = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");
        int queryUserRole = 0;

        //获取用户列表
        UserServiceImpl userService = new UserServiceImpl();
        List<User> userList = null;

        //第一次的请求为第一页，页面固定
        int pageSize = 5; //可以写在配置文件中，方便后期修改；
        int currentPageNo = 1;

        if (queryUserName == null) {
            queryUserName = "";
        }
        if (temp != null && !temp.equals("")) {
            queryUserRole = Integer.parseInt(temp); //给查询赋值！
        }
        if (pageIndex != null) {
            currentPageNo = Integer.parseInt(pageIndex);
        }

        //获取用户的总数(分页： 上一页,下一页)
        int totalCount = userService.getUserCount(queryUserName, queryUserRole);
        //总页数支持
        PageSupport pageSupport = new PageSupport();
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);
        pageSupport.setCurrentPageNo(currentPageNo);
        int totalPageCount = pageSupport.getTotalPageCount();
        //控制首页和尾页
        //如果页面要小于1了，就显示第一页的东西
        if (currentPageNo < 1) {
            currentPageNo = 1;
        } else if (currentPageNo > totalPageCount) { //当前页面大于了最后一页
            currentPageNo = totalPageCount;
        }
        //获取用户列表展示
        userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, pageSize);
        req.setAttribute("userList", userList);

        RoleServiceImpl roleService = new RoleServiceImpl();
        List<Role> roleList = roleService.getRoleList();
        req.setAttribute("roleList", roleList);
        req.setAttribute("totalCount", totalCount);
        req.setAttribute("currentPageNo", currentPageNo);
        req.setAttribute("totalPageCount", totalPageCount);
        req.setAttribute("queryUserName", queryUserName);
        req.setAttribute("queryUserRole", queryUserRole);
        //返回前端
        req.getRequestDispatcher("userlist.jsp").forward(req, resp);

    }
    //得到用户角色列表
    public void getRoleList(HttpServletRequest req, HttpServletResponse resp) throws SQLException, ClassNotFoundException {
        RoleService roleService = new RoleServiceImpl();
        List<Role> roleList = roleService.getRoleList();
        try {
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            writer.print(JSON.toJSONString(roleList));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //通过用户编码查询用户是否存在
    public void userCodeExist(HttpServletRequest req, HttpServletResponse resp) throws SQLException, ClassNotFoundException, IOException {
        UserServiceImpl userService = new UserServiceImpl();
        User user = userService.getUserByUserCode(req.getParameter("userCode"));
        Map<String, String> resultMap = new HashMap<>();
        if (user.getUserCode() == null) {
            resultMap.put("userCode", "notExist");
        } else {
            resultMap.put("userCode", "exist");
        }
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        writer.write(JSON.toJSONString(resultMap));
        writer.flush();
        writer.close();
    }

    //通过用户Id查询用户
    public void getUserById(HttpServletRequest req, HttpServletResponse resp) throws SQLException, ClassNotFoundException, ServletException, IOException {
        int id = 0;
        String id1 = req.getParameter("uid"); //视图查看
        String id2 = req.getParameter("id");// 用于区分转发到查看用户界面还是修改用户界面,修改
        System.out.println("id1: " + id1 + "   id2:" + id2);
        if (id1 == null) {// 修改用户信息
            id = Integer.parseInt(id2);
        } else {
            id = Integer.parseInt(id1);
        }
        User user = null;
            UserService userService = new UserServiceImpl();
            user = userService.getUserById(id);
        BaseDao baseDao = new BaseDao();
        baseDao.closeAll();
        req.setAttribute("user", user);
        if (id1 != null) {
            req.getRequestDispatcher("userview.jsp").forward(req, resp);
        } else {
            req.getRequestDispatcher("usermodify.jsp").forward(req, resp);
        }
    }

    //添加用户
    public void addUser(HttpServletRequest req, HttpServletResponse resp) throws ParseException, SQLException, ClassNotFoundException, ServletException, IOException {
        System.out.println("进入到addUser函数");
        String userCode = req.getParameter("userCode");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");

        User user = new User();
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setAddress(address);
        user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        user.setGender(Integer.valueOf(gender));
        user.setPhone(phone);
        user.setUserRole(Integer.valueOf(userRole));
        user.setCreationDate(new Date());
        user.setCreatedBy(((User) req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        user.setModifyBy(user.getCreatedBy());
        user.setModifyDate(new Date());
        UserServiceImpl userService = new UserServiceImpl();

        if (userService.addUser(user) == 1){
            resp.sendRedirect(req.getContextPath() + "/jsp/user.do?method=query");
        }else {
            req.getRequestDispatcher("useradd.jsp").forward(req,resp);
        }

    }

    //修改用户
    public void modifyUser(HttpServletRequest req, HttpServletResponse resp) throws SQLException, ClassNotFoundException, IOException, ParseException {
        String userCode = req.getParameter("userCode");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");
        int id = Integer.parseInt(req.getParameter("uid"));

        User user = new User();
        user.setId(id);
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setAddress(address);
        user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        user.setGender(Integer.valueOf(gender));
        user.setPhone(phone);
        user.setUserRole(Integer.valueOf(userRole));
        user.setModifyBy(((User) req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        user.setModifyDate(new Date());

        UserService userService = new UserServiceImpl();
        int i = userService.modifyUser(user);
        if (i>0){
            resp.sendRedirect(req.getContextPath() + "/jsp/user.do?method=query");
        }else {
            resp.sendRedirect("usermodify.jsp");
        }

    }

    //删除用户
    public void delUser(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        int id = Integer.parseInt(req.getParameter("uid"));
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if (id <= 0) {
            resultMap.put("delResult", "notexist");
        } else {
            UserService userService = new UserServiceImpl();
            if (userService.delUser(id) == 1) {
                resultMap.put("delResult", "true");
            } else {
                resultMap.put("delResult", "false");
            }
        }

        //把resultMap转换成json对象输出
        resp.setContentType("application/json");
        PrintWriter outPrintWriter = resp.getWriter();
        outPrintWriter.write(JSONArray.toJSONString(resultMap));
        outPrintWriter.flush();
        outPrintWriter.close();
    }

    }

